package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.basicinfo.ProductMapper;
import com.ruikong.dazhi.entity.basicinfo.Product;

import com.ruikong.dazhi.model.input.ProductPageInput;
import com.ruikong.dazhi.service.basicinfo.IProductService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Executable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * (Product)表服务实现类
 *
 * @author makejava
 * @since 2021-11-10 15:35:16
 */
@Service
public class ProductServiceImpl implements IProductService {
    @Resource
    private ProductMapper productMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Product queryById(Integer id) {
        return this.productMapper.queryById(id);
    }



    /**
     * 新增数据
     *
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(Product product) {
        product.setIsDeleted(0);
      return   this.productMapper.insert(product);

    }

    /**
     * 修改数据
     *
     * @param product 实例对象
     * @return 实例对象
     */
    @Override
    public int update(Product product) {
      return   this.productMapper.update(product);

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.productMapper.deleteById(id) > 0;
    }

    @Override
    public PageInfo<Product> productPageInfo(ProductPageInput input) {

        PageHelper.startPage(input.getPageNumber(),input.getPageSize());
        List<Product>  products=this.productMapper.selectProductPage(input);
        PageInfo pageInfo=new PageInfo(products);
        return pageInfo;
    }

    @Override
    public boolean isExist(Product product) {
        return this.productMapper.isExist(product)>0;
    }

    @Override
    public BaseResult productImport(MultipartFile multipartFile) {
        BaseResult baseResult=new BaseResult();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            //存放产品集合用于批次保存
            List<Product> products=new ArrayList<>();
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }

                //新建产品对象
                Product product=new Product();
                //is_deleted设置为0
                product.setIsDeleted(0);

                //产品编号
                cell = row.getCell(0);
                String productSn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，产品编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    productSn = cell.getStringCellValue().trim();
                    product.setProductSn(productSn);
                    if (productMapper.isExist(product) > 0) {
                        baseResult.setMsg(String.format("错误！表格第%s行，产品编号已存在", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }
                }


                //产品名称
                cell = row.getCell(1);
                String productName;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，产品名称不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    productName = cell.getStringCellValue().trim();
                    product.setProductName(productName);
                }

                //产品批次
                cell = row.getCell(2);
                String productBatch;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    productBatch = cell.getStringCellValue().trim();
                    product.setProductBatch(productBatch);
                }



                //简称
                cell = row.getCell(3);
                String abbreviation;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    abbreviation = cell.getStringCellValue().trim();
                    product.setAbbreviation(abbreviation);
                }


                //性状
                cell = row.getCell(4);
                String shape;
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    shape = cell.getStringCellValue().trim();
                    product.setProductShape(shape);
                }


                //制造日期
                cell = row.getCell(5);
                Date manufactureDate ;
                if (cell != null) {
                    manufactureDate = cell.getDateCellValue();
                    product.setManufactureDate(manufactureDate);
                }else
                {
                    product.setManufactureDate(null);
                }


                products.add(product);
            }

            batchSaveProduct(products);
            file.delete();
            baseResult.setCode(ResultApi.successCode);
            baseResult.setMsg("导入成功");

        }catch (Exception e){
            baseResult.setMsg("产品导入时出错");
            baseResult.setCode(ResultApi.errorCode);
            e.printStackTrace();
        }
        return baseResult;
    }



    /**
     * @author Hassion.Tang
     * @params
     * @return
     * @exception
     * @date 2021/11/11 14:18
     * @description 批次保存
    */

    public void  batchSaveProduct(List<Product> products){
        products.stream().forEach(x->this.productMapper.insert(x));
    }




}
